import axios from 'axios'
import store from '@/store'
import {getTime} from '@/utils/auth'
import { Message } from 'element-ui'
import router from '@/router'
import {removTime} from '@/utils/auth'
const instance = axios.create({
        baseURL:process.env.VUE_APP_BASEURL
})
const time=30*60*1000
// const time=2*1000
instance.interceptors.request.use(
    config => {
        const date_time = Date.now()
        const token_time = getTime()
        const date=date_time-token_time
        if (date>time) {
            Message({
                message: 'token过期，请重新登入',
                type: 'error'
            });
            store.dispatch('user/logout')
            removTime()
            router.push(`/login?_redirect=${window.location.href.split('#')[1]}`)
        }
        const token = store.getters.token
        if (token) {
            config.headers.Authorization=`Bearer ${token}`
        }
         return config
    },
    err => {
        return Promise.reject(err)
    }
)
instance.interceptors.response.use(
    response => {
        // 验证用户密码是否正确，正确就进行跳转
        let { message, success } = response.data
        if (success) {
            return response.data
        } else {
            // 错误信息的弹窗
            Message({
                message: '错了哦，这是一条错误消息',
                type: 'error'
              });

            return Promise.reject(new Error(message))
        }
        
    },
    err => {
        return Promise.reject(err)
    }
)
 export default instance